<?php

namespace backend\controllers;

use backend\models\form\ChangeDealUserForm;
use backend\models\form\FeedForm;
use backend\service\AuthService;
use backend\service\FeedService;
use backend\service\UserEvaluService;
use common\models\Feed;
use common\service\ConstatService;
use common\service\Csv;
use Composer\Package\Loader\ValidatingArrayLoader;
use dosamigos\qrcode\lib\Enum;
use dosamigos\qrcode\QrCode;
use yii\helpers\Url ;
use Yii;
use yii\web\UploadedFile;


/**
 * 反馈问题
 */
class FeedController extends BaseController
{

    /**
     * 问题列表
     */
    public function actionIndex(){
        $limit = 20 ;
        $searchData = Yii::$app->request->get() ;

        $user_id = Yii::$app->admin->identity->user_id ;
        $cookies = Yii::$app->request->cookies;//注意此处是request
        $uuid = $cookies->get('user_id', null);//设置默认值
        if(empty($uuid)){
            $time = 3600*24*7 ;
            $cookies = Yii::$app->response->cookies;
            $cookies->add(new \yii\web\Cookie([
                'name' => 'useruuid',
                'value' => $user_id,
                'expire'=>time()+$time,
                'domain' => "lienm.com"
            ]));
        }

        $typeId = Yii::$app->admin->identity->type_id ;
        if($typeId==ConstatService::ADMIN_USER_TYPE_ID_MANAGER || ConstatService::ADMIN_USER_TYPE_ID_SUPER_ADMIN){
            //管理员添加是已审核
        }else{
            //普通员工添加是未审核
        }

        $orderBy = "static asc,id asc" ;
        $feedArr = FeedService::findFeedList($limit,$searchData,$orderBy) ;
        return $this->render('index', ['feedArr' => $feedArr,"limit"=>$limit]);
    }

    /**
     *  添加反馈
     */
    public function actionAddFeed(){
        $model = new FeedForm();
        if(!Yii::$app->request->isPost) {
            return $this->renderPartial('add_feed', ['model'=>$model]);
        }
        if ($model->load(\Yii::$app->request->post()) && $model->validate()){
            $model->pic_url1  = UploadedFile::getInstance($model, 'pic_url1');
            $model->pic_url2  = UploadedFile::getInstance($model, 'pic_url2');
            $model->pic_url3  = UploadedFile::getInstance($model, 'pic_url3');
            $model->video_url = UploadedFile::getInstance($model, 'video_url');
            $result = $model->add();
            if ($result['code']==200) {
                return $this->returnAjax(200, $result['msg'], Url::toRoute("/feed/index"));
            } else {
                return $this->returnAjax(400, $result['msg'], Url::toRoute("/feed/index"));
            }
        }
        return $this->returnAjax(400, current($model->getFirstErrors()), Url::toRoute("/feed/index"));
    }


    /**
     *  修改反馈
     */
    public function actionEditFeed(){
        $model = new FeedForm();

        $feed_id = Yii::$app->request->get("id");
        $feed = Feed::findOne(["id"=>$feed_id]);
        if(empty($feed)){
            return $this->returnAjax(400, "无此工单", Url::toRoute("/feed/index"));
        }

        if(Yii::$app->request->isPost) {
            if ($model->load(\Yii::$app->request->post()) && $model->validate()){
                $model->pic_url1  = UploadedFile::getInstance($model, 'pic_url1');
                $model->pic_url2  = UploadedFile::getInstance($model, 'pic_url2');
                $model->pic_url3  = UploadedFile::getInstance($model, 'pic_url3');
                $model->video_url = UploadedFile::getInstance($model, 'video_url');
                $result = $model->edit($feed_id);
                if ($result['code']==200) {
                    return $this->returnAjax(200, $result['msg'], Url::toRoute("/feed/index"));
                } else {
                    return $this->returnAjax(400, $result['msg'], Url::toRoute("/feed/index"));
                }
            }
        }

        $model->setAttributes($feed->getAttributes());
        return $this->renderPartial('edit_feed',["model"=>$model]);
    }

    /**
     * 删除反馈
     */
    public function actionDel(){
        $id = Yii::$app->request->get("id");

        if(empty($id)){
            return $this->returnAjax(400,'缺少参数') ;
        }

        $feed = Feed::find()->where(['id'=>$id])->one();

        if(empty($feed)){
            return $this->returnAjax(400,'没有该数据') ;
        }

        $rs = $feed->delete();

        if($rs){
            return $this->returnAjax(200,'删除成功', Url::toRoute("/feed/index")) ;
        }else{
            return $this->returnAjax(400,'删除失败') ;
        }
    }

    /**
     * 审核
     */
    public function actionVerify(){
        $id = Yii::$app->request->get("id");

        if(empty($id)){
            return $this->returnAjax(400,'缺少参数') ;
        }

        $feed = Feed::find()->where(['id'=>$id])->one();

        if(empty($feed)){
            return $this->returnAjax(400,'没有该数据') ;
        }

        Feed::updateAll(["verify"=>ConstatService::FEED_VERIFY_VERIFYED],["id"=>$id]) ;

        return $this->returnAjax(200,'审核成功', Url::toRoute("/feed/index")) ;

    }

    /**
     *  完成反馈
     */
    public function actionFinish(){
        $id = Yii::$app->request->get("id");

        if(empty($id)){
            return $this->returnAjax(400,'缺少参数') ;
        }

        $feed = Feed::findOne(["id"=>$id]) ;
        if(empty($feed)){
            return $this->returnAjax(400,'反馈不存在') ;
        }

        if(Yii::$app->admin->identity->username!="admin"){
            if($feed['deal_user_id']!=Yii::$app->admin->identity->user_id){
                return $this->returnAjax(400,'您不是该单的处理人，无法点完成') ;
            }
        }

        if($feed['static']==ConstatService::FEED_STATIC_DEALED){
            return $this->returnAjax(400,'已显示过二维码，无法再显示') ;
        }

        $file = date("Ymd").rand(10000,99999).".png" ;
        $saveUrl = Yii::getAlias("@webroot")."/upload/qcode/".$file ;
        $hostname = Yii::$app->request->hostInfo ;
        $webUrl = $hostname ."/upload/qcode/".$file ;
        //生成二维码
        $user_id = Yii::$app->admin->identity->user_id ;

        $curtime = strtotime("now") ;
        $qUrl = Yii::$app->params["siteUrl"] ."/site/evalu.html?id={$id}&user_id={$user_id}&time={$curtime}" ;
//        echo $qUrl ;exit;
        QrCode::png($qUrl,$saveUrl,Enum::QR_ECLEVEL_L,8,2);

        $session = Yii::$app->session;
        $session->set('user_id', $user_id);

//        echo ($qUrl);
        //更新为完成
        Feed::updateAll(["static"=>ConstatService::FEED_STATIC_DEALED],["id"=>$id]) ;

        return $this->returnAjax(200,'成功', $webUrl) ;
    }

    /**
     *  反馈详情
     */
    public function actionDetail(){
        $url = empty(Yii::$app->request->referrer)?Url::toRoute(["/feed/index"]):Yii::$app->request->referrer ;
        $id = Yii::$app->request->get("id");
        if(empty($id)){
            return $this->redirect(["/tip/index", "msg" => "反馈不存在", "url" => $url]);
        }

        $feed = Feed::find()->where(['id'=>$id])->one();

        if(empty($feed)){
            return $this->redirect(["/tip/index", "msg" => "反馈不存在~", "url" => $url]);
        }

        $model = new ChangeDealUserForm() ;
        $model->deal_user_id = empty($feed['deal_user_id'])?null:$feed['deal_user_id'];

        return $this->render('detail', compact("feed","model"));
    }

    /**
     * 修改处理人
     */
    public function actionChangeDealUser(){
        $id = Yii::$app->request->get("id","") ;
        if(empty($id)){
            return $this->returnAjax(self::FAIL, "请不要乱操作");
        }

        $model = new ChangeDealUserForm() ;

        $post_data = Yii::$app->request->post();
        if ($model->load($post_data) && $model->validate()) {
            $addRs = $model->changeUser($id);
            if($addRs['code']==200){
                $url = empty(Yii::$app->request->referrer)?Url::toRoute(["/feed/index"]):Yii::$app->request->referrer ;
                return $this->returnAjax(self::SUCCESS, '成功', $url);
            }else{
                return $this->returnAjax(self::FAIL, $addRs['msg']);
            }
        }else{
            return $this->returnAjax(self::FAIL, "请不要乱操作");
        }
    }

    /**
     * 评价历史
     */
    public function actionHistory(){
        $url = empty(Yii::$app->request->referrer)?Url::toRoute(["/feed/index"]):Yii::$app->request->referrer ;
        $id = Yii::$app->request->get("id");
        if(empty($id)){
            return $this->redirect(["/tip/index", "msg" => "反馈不存在", "url" => $url]);
        }

        $feed = Feed::find()->where(['id'=>$id])->one();

        if(empty($feed)){
            return $this->redirect(["/tip/index", "msg" => "反馈不存在~", "url" => $url]);
        }

        $searchData["feed_id"] = $id ;
        $arr = UserEvaluService::findEvaluList(100,$searchData,"id asc") ;
        $list = $arr['list'] ;

        return $this->render('history', compact("list"));
    }

    /**
     * 导出评价
     */
    public function actionExport(){
        ini_set('memory_limit', '2048M');

        $limit = 60000;

        if (Yii::$app->request->isPost) {
            $searchData = Yii::$app->request->post() ;
        }else{
            $searchData = Yii::$app->request->get() ;
        }

        $orderBy = "id desc" ;
        $arr = UserEvaluService::exportEvalu($searchData,$orderBy) ;

        $orderBy = "static asc,id asc" ;
        $arr = FeedService::exportFeed($searchData,$orderBy) ;


        $totalCount = $arr['count'] ;

        if (Yii::$app->request->isPost) {
            if ($totalCount > $limit) {
                return $this->returnAjax(self::FAIL, "您导出的数据大于{$limit}条, 请先进行筛选!");
            }
            return $this->returnAjax(self::SUCCESS, '', Url::toRoute(["/feed/export"]), compact('totalCount'));
        }

        if ($totalCount > $limit) {
            return $this->returnAjax(self::FAIL, "您导出的数据大于{$limit}条, 请先进行筛选!");
        }

        $name = "反馈列表" ;
        $models = $arr['query'] ;
        Csv::export([
            'models' => $models,
            'fileName' => date('Y-m-d').$name,
            'columns' => ['id','desc','static','add_time','company_name','contact_name','contact'],
            'headers' => [
                'id'           => '序号',
                'desc'         => '问题描述',
                'static'       => '状态',
                'add_time'     => '添加时间',
                'company_name' => '报修公司',
                'contact_name' => '联系人',
                'contact'      => '联系电话',
            ]
        ], function (&$models) {
            $num = 1 ;
            $statusArr = ConstatService::FEED_STATIC_COLOR_ARR;
            foreach ($models as $key => $data) {
                $models[$key]['id'] = $num;
                $models[$key]['add_time'] = "\t" . $data['add_time'];
                $models[$key]['contact'] = "\t" . $data['contact'];
                $models[$key]['static'] = empty($statusArr[$data['static']])?"":strip_tags($statusArr[$data['static']]);
                $num = $num + 1;
            }
        },true);

        Yii::$app->end();
    }


}
